//
//  ComposeViewController.swift
//  weibo
//
//  Created by mac on 15/12/23.
//  Copyright (c) 2015年 LYR. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    @objc private func close() {
      dismissViewControllerAnimated(true, completion: nil)
    }
    
    //  点击选择图片按钮
    @objc private func selectPicture() {
        
        print("选择图片")
    
    //  隐藏键盘
        textView.resignFirstResponder()
        
        //更新图片选择器的高度
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenH / 3 * 2)
        }
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            //  刷新
            self.view.layoutIfNeeded()
        })
        
    }
    
    @objc private func send() {
    
        var urlString = "2/statuses/update.json"
        
        guard let token = UserAccountViewModel().access_token else {
            SVProgressHUD.showInfoWithStatus("请重新登录",maskType: .Gradient)
            return
        
        }
        
        let parameter = ["access_token" : token,"status" : textView.text ?? ""]
        
        // 有图片的时候
        if pictureSelectorVC.imageList.count != 0 {
        //上传图片
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)
            
            NetworkTools.sharedTools.uploadImage(urlString, paraments: parameter, imageData: imageData!, finished: { (dict, error) -> () in
             self.finishedUpdateStatus(dict, error: error)
                
            })
            
        }else {
            NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameter) { (dict, error) -> () in
            
                self.finishedUpdateStatus(dict, error: error)
            
            }
        
        
         }
    }
    
    private func finishedUpdateStatus(dict: [String : AnyObject]?,error: NSError?) {
        if error != nil {
            SVProgressHUD.showInfoWithStatus("发布微博失败,请检查网络", maskType: .Gradient)
            return
        }
        SVProgressHUD.showSuccessWithStatus("发布微博成功", maskType: .Gradient)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    //   view 已经出现
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if pictureSelectorVC.imageList.count == 0 {
        
        textView.becomeFirstResponder()
        }
    }
    
    // 懒加载子视图
    private lazy var textView: UITextView = {
    
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.randomColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        return tv
        
    }()
    //懒加载 输入文本框
    private lazy var placeHoderLabel: UILabel = UILabel(title: "输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18, margin: 0)
    // 懒加载 toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //  照片选择qi
    private lazy var pictureSelectorVC: PictureSelectViewController = PictureSelectViewController()

    //析构函数
    deinit {
       NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}

extension ComposeViewController: UITextViewDelegate {
    //要实时监测文本的改变
    func textViewDidChange(textView: UITextView) {
        
        //根据 textView是否有文本 隐藏占位文本  开启发送按钮的交互
        placeHoderLabel.hidden = textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }

}

extension ComposeViewController {

    //设置界面
    private func setupUI() {
        //设置背景色
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        
        setupToolBar()
        
        setPictureSelectorVC()
        
        //注册通知
        registerNotification()
    }
    
    // 设置照片选择器
    private func setPictureSelectorVC() {
    
        // 首先添加视图控制器
        addChildViewController(pictureSelectorVC)
        
        //添加视图控制器的根控制器
        view.addSubview(pictureSelectorVC.view)
        
        //将 toolBar 移动到视图的最顶层
        view.bringSubviewToFront(toolBar)
        
        //设置约束和布局
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
            
        }
    }
    
    //  注册通知
    private func registerNotification() {
      NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    
    //  键盘高度将要发生改变
    @objc private func keyboardWillChange(n: NSNotification) {
     let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //print("\(endRect.origin.y)")
        
        let offsetY = -screenH + endRect.origin.y
        
        //移动 toolBar 的位置   需要改变 toolBar 的约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        UIView.animateWithDuration(duration, animations: { () -> Void in
            
            // 强制刷新
            self.view.layoutIfNeeded()
        })
    }
    
    
    // 自定义toolBar
    private func  setupToolBar() {
        
        //给toolBar 设置  items 数组
        var items = [UIBarButtonItem]()
        
        //向数组中添加元素
        let itemSettings = [["imageName" : "compose_toolbar_picture","actionName" : "selectPicture"],
            ["imageName" : "compose_mentionbutton_background"],
            ["imageName" : "compose_trendbutton_background"],
            ["imageName" : "compose_emoticonbutton_background"],
            ["imageName" : "compose_add_background"]]
        
        //遍历配置的数组
        for item in itemSettings {
            let imageName = item["imageName"]
            let itemBtn = UIButton(imageName: nil, backImageName: imageName!)
            
            if let action = item["actionName"] {
                itemBtn.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
            let barButtonItem = UIBarButtonItem(customView: itemBtn)
            
            items.append(barButtonItem)
            
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        //移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
        //添加到父视图
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            
        }
        
    }
    
    private func setTextView() {
        //添加 textview
        view.addSubview(textView)
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(screenH / 3)
            
        }
        
        // 给textView  添加文本
        textView.addSubview(placeHoderLabel)
        placeHoderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
        }
        
    }
    
    // 设置导航条
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        
        //默认发送按钮不允许交互
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        //自定义titleView
        let titleLable = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17)
        let nameLable = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        
        //添加label
        titleView.addSubview(titleLable)
        titleView.addSubview(nameLable)
        
        //设置约束
        titleLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLable.snp_makeConstraints{ (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    
    }

}